import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';

import { Button, Checkbox, Col, Form, message, Popconfirm, Row, Table, Tooltip } from 'antd';
import { withRouter } from 'umi';
import Store from 'store';
import { BottomAction } from '@/components';
import IconFont from '@/components/IconFont';
import UploadOss from '@/components/UploadOss';
import { defaultFormatResult, useRequest } from '@/hooks';
import EmployeeCard from '@/pages/EntryManage/components/EmployeeCard';
import useCandidateProcess from '@/pages/EntryManage/hooks/useCandidateProcess';
import { genID, saveFile } from '@/utils/utils';

import Card from '../components/Card';
import { PreviewModal } from '../components/Preview';
import {
    fetchDealEntryByHR,
    fetchEmployeeEntryMaterials,
    fetchSaveFileRelation,
    removeFileRelationByCategoryCode
} from '../services';
import { getFileType, replaceToWaitEntry } from '../utils';
import styles from './index.less';

const formItemLayout = {
    labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
    },
    wrapperCol: {
        xs: { span: 24 },
        sm: { span: 15 }
    }
};

const SIGNED = 1;
const NOT_SIGNED = 0;

const ELECTRON_MATERIAL = '0';
const ENTITY_MATERIAL = '1';
const OTHER_MATERIAL = 'other';

// 入职环节5;
const PROCESS_STATUS = 5;

/**
 * 办理入职
 *
 * @param {Object} form - form表单
 */
const HRLink = ({ form, location }) => {
    const { getFieldDecorator } = form;
    const [electronMaterials, setElectronMaterials] = useState([]);
    const [entityMaterials, setEntityMaterials] = useState([]);
    const [otherFileList, setOtherFileList] = useState([]);
    const [fileUploading, setFileUploading] = useState(false);
    const [isSignedContractState, setIsSignedContractState] = useState(false);
    const [otherMaterialsConfig, setOtherMaterialsConfig] = useState({});
    const [contractProviewProps, setContractProviewProps] = useState({});
    const [contractProviewVisible, setContractProviewVisible] = useState(true);

    const previewRef = useRef();
    const { query = {} } = location;
    const { entryPersonnelCode, organizationCode } = query;

    const user = JSON.parse(localStorage.getItem('user') || '{}');
    const { employeeCode } = user;

    const onClose = () => {
        Store.set('contractPreview', true);
        setContractProviewVisible(false);
    };

    useEffect(() => {
        const hasCacheField = Store.get('contractPreview');
        if (!hasCacheField) {
            setContractProviewProps({
                title: (
                    <div className={styles.tooltipContent}>
                        <p>这里可以预览合同</p>
                        <p>预览后支持打印，便于签署。</p>
                        <div onClick={onClose}>我知道了</div>
                    </div>
                ),
                visible: true,
                overlayClassName: `${styles.tooltipCls}`,
                getPopupContainer: triggerNode => triggerNode.parentElement
            });
        } else if (contractProviewVisible) {
            setContractProviewProps({
                title: '预览（支持打印）'
            });
        } else {
            setContractProviewProps({
                visible: false
            });

            setContractProviewVisible(true);
        }
    }, [contractProviewVisible]);

    const canAction = useCandidateProcess(entryPersonnelCode, PROCESS_STATUS, employeeCode);

    const fetchLaborContractSuccess = result => {
        const { code, msg } = result;
        if (code === 10000) {
            message.success(msg);
            replaceToWaitEntry();
        } else {
            message.error(msg);
        }
    };

    // 获取员工入职材料
    const {
        run: getEmployeeEntryMaterials,
        data: employeeEntryMaterialsDataSource,
        loading: materialsLoading
    } = useRequest(param => fetchEmployeeEntryMaterials(param), {
        manual: true,
        ...defaultFormatResult
    });

    const {
        contractResCombineBusinessResourceLocalDto: contractTemplate = [],
        employeeEntryMaterialListRespVO: materials = [],
        isSignedContract: isSigned
    } = employeeEntryMaterialsDataSource || {};

    // 合同模板
    const laborContract = useMemo(() => {
        if (Array.isArray(contractTemplate)) {
            return contractTemplate[0]?.urlList[0] || {};
        }
        return {};
    }, [contractTemplate]);

    useEffect(() => {
        setIsSignedContractState(!!isSigned);
    }, [isSigned]);

    // 获取材料列表
    useEffect(() => {
        // 获取其他材料
        const getOtherMaterials = (result = {}) => {
            const {
                uploadCountLimit,
                uploadFormatLimit,
                uploadFormatTip,
                uploadTip,
                materialCode: categoryCode = ''
            } = result;
            const { urlList = [] } = result.resCombineBusinessResourceLocalDto || {};
            const uploadedOtherContract = urlList.map(item => {
                const { url, originName, keyName } = item;
                return {
                    uid: genID(),
                    keyName,
                    name: originName,
                    status: 'done',
                    url,
                    originName
                };
            });
            return [
                uploadedOtherContract,
                { uploadCountLimit, uploadFormatLimit, uploadFormatTip, uploadTip, categoryCode }
            ];
        };

        if (materials.length) {
            const electronResult = materials.filter(item => item.group === ELECTRON_MATERIAL);
            const entityResult = materials.filter(item => item.group === ENTITY_MATERIAL);
            const otherResult = materials.find(item => item.group === OTHER_MATERIAL);
            const [otherMaterials, materialsConfig] = getOtherMaterials(otherResult);
            setElectronMaterials(electronResult);
            setEntityMaterials(entityResult);
            setOtherFileList(otherMaterials);
            setOtherMaterialsConfig(materialsConfig);
        }
    }, [materials]);

    // 删除入职材料成功后回调
    const fetchRemoveMaterialSuccess = result => {
        const { code, msg } = result;
        if (code === 10000) {
            getEmployeeEntryMaterials(entryPersonnelCode);
            message.success('删除成功');
        } else {
            message.error(msg);
        }
    };

    // 上传入职材料成功后回调
    const fetchUploadMaterialsFileSuccess = result => {
        const { code, msg } = result;
        if (code === 10000) {
            getEmployeeEntryMaterials(entryPersonnelCode);
            message.success('上传成功');
        } else {
            message.error(msg);
        }
        setFileUploading(false);
    };

    // 提交
    const { run: saveLaborContract, loading: submitLoading } = useRequest(param => fetchDealEntryByHR(param), {
        manual: true,
        onSuccess: fetchLaborContractSuccess
    });

    // 删除材料
    const { run: removeMaterial, loading: deleteLoading } = useRequest(
        param => removeFileRelationByCategoryCode(param),
        {
            manual: true,
            onSuccess: fetchRemoveMaterialSuccess
        }
    );

    // 上传材料
    const { run: UploadMaterialsFile, loading: uploadLoading } = useRequest(param => fetchSaveFileRelation(param), {
        manual: true,
        onSuccess: fetchUploadMaterialsFileSuccess
    });

    const loading = useMemo(() => materialsLoading || uploadLoading || deleteLoading || submitLoading, [
        materialsLoading,
        uploadLoading,
        deleteLoading,
        submitLoading
    ]);

    // 根据入职人员信息及机构代码获取数据
    useEffect(() => {
        if (entryPersonnelCode && organizationCode) {
            getEmployeeEntryMaterials(entryPersonnelCode);
        } else {
            replaceToWaitEntry('参数错误');
        }
    }, [entryPersonnelCode, getEmployeeEntryMaterials, organizationCode]);

    // 删除文件
    const handleDeleteFile = file => {
        removeMaterial(file);
    };

    // 预览文件
    const handlePreview = source => {
        onClose();
        const { keyName, url, originName } = source;
        const fileType = getFileType(keyName);
        previewRef.current.open({
            type: fileType,
            title: keyName,
            origin: url,
            encode: fileType === 'office',
            originName
        });
    };

    // 下载附件
    const handleDownload = useCallback(urlList => {
        urlList.forEach(item => {
            saveFile(item.url, item.originName);
        });
    }, []);

    const columns = [
        {
            title: '名称',
            dataIndex: 'materialName',
            render: (text, record) => {
                const { resourcesNumber } = record;
                return (
                    <div className="padding-16">
                        {text}
                        {resourcesNumber}
                    </div>
                );
            }
        },
        {
            title: '材料',
            dataIndex: 'resCombineBusinessResourceLocalDto',
            className: 'fileColumn',
            render: (value = {}) => {
                const { urlList: files = [], categoryCode } = value;

                return (
                    <div className={styles.filesWrapper}>
                        {files.length ? (
                            files.map((file = {}) => (
                                <div className="file">
                                    <div className="fileBox">
                                        <span className="fileName" onClick={() => handlePreview(file)}>
                                            {file.originName}
                                        </span>
                                        <IconFont
                                            className="previewFile"
                                            onClick={() => handlePreview(file)}
                                            icon="iconlistfunction_view_icon_default"
                                        />
                                    </div>
                                    {canAction && (
                                        <Popconfirm
                                            placement="top"
                                            title="是否删除文件"
                                            onConfirm={() => {
                                                handleDeleteFile({
                                                    businessCode: 'EntryMaterials',
                                                    categoryCode,
                                                    ids: [entryPersonnelCode],
                                                    keyName: file.keyName,
                                                    sysCode: 'OA'
                                                });
                                            }}
                                            okText="是"
                                            cancelText="否"
                                        >
                                            <span className="deleteFile">
                                                <IconFont icon="iconshanchu" />
                                            </span>
                                        </Popconfirm>
                                    )}
                                </div>
                            ))
                        ) : (
                            <div className="noFile padding-16">未上传</div>
                        )}
                    </div>
                );
            }
        },
        {
            title: '操作',
            dataIndex: 'active',
            width: 100,
            render: (text, record) => {
                const {
                    resCombineBusinessResourceLocalDto = {},
                    uploadCountLimit = 0,
                    uploadFormatLimit,
                    uploadFormatTip,
                    materialCode: categoryCode
                } = record;
                const { urlList = [] } = resCombineBusinessResourceLocalDto;

                return (
                    <div className={styles.uploadWrapper}>
                        <UploadOss
                            uploadUrl="/api/resource/public/oss/producePutPreSignUrls"
                            dragAble={false}
                            checkFileSize={10}
                            checkFileSizeMsg="文件大小不可超过10M，请重新选择"
                            sysCode="OA"
                            businessCode="SysAvatar"
                            categoryCode={categoryCode}
                            isSingle
                            showPreviewFile
                            checkFileType={uploadFormatLimit}
                            checkFileTypeMsg={uploadFormatTip}
                            onUploaded={async (file = []) => {
                                try {
                                    setFileUploading(true);
                                    await UploadMaterialsFile({
                                        businessCode: 'EntryMaterials',
                                        entityId: entryPersonnelCode,
                                        list: [
                                            {
                                                categoryCode,
                                                keyNameAndOpt: [`ADD:${file[0]?.keyName}`]
                                            }
                                        ],
                                        sysCode: 'OA'
                                    });
                                } catch (error) {
                                    message.error(error.message);
                                }
                            }}
                            setFileList={(files = []) => {
                                if (files.filter(item => item.status === 'uploading').length > 0) {
                                    setFileUploading(true);
                                }
                            }}
                            // prettier-ignore
                            // eslint-disable-next-line no-nested-ternary, max-len
                            disabled={!canAction ? true : fileUploading ? true : !uploadCountLimit ? true : urlList.length >= uploadCountLimit }
                        >
                            <Button
                                type="link"
                                disabled={
                                    // prettier-ignore
                                    // eslint-disable-next-line no-nested-ternary, max-len
                                    !canAction ? true : fileUploading ? true : !uploadCountLimit ? true : urlList.length >= uploadCountLimit
                                }
                                className={styles.uploadButton}
                            >
                                <IconFont icon="iconoa_form_bnt_upload" />
                            </Button>
                        </UploadOss>

                        {!!urlList?.length && (
                            <Button
                                type="link"
                                disabled={!canAction || fileUploading}
                                className={styles.uploadButton}
                                onClick={() => handleDownload(urlList)}
                            >
                                <IconFont icon="download" className={styles.downloadIcon} />
                            </Button>
                        )}
                    </div>
                );
            }
        }
    ];

    // 取消跳转到待入职列表
    const handleCancel = () => {
        replaceToWaitEntry();
    };

    const handleSaveLaborContract = () => {
        form.validateFieldsAndScroll(
            null,
            {
                scroll: {
                    offsetBottom: 80
                }
            },
            async (err, values) => {
                if (!err) {
                    const { isSignedContract } = values;
                    saveLaborContract({
                        currentHandlerEmployeeCode: employeeCode,
                        isSignedContract: isSignedContract ? SIGNED : NOT_SIGNED,
                        entryPersonnelCode
                    });
                }
            }
        );
    };

    const handleSignedChange = e => {
        setIsSignedContractState(e.target.checked);
    };

    return (
        <div className={styles.hrLinkWrapper}>
            <div className={styles.employeeInfo}>
                <div className={styles.employeeInfoBox}>
                    <EmployeeCard employeeCode={entryPersonnelCode} />
                </div>
            </div>
            <Card title="收集入职材料" headBorder bordered={false}>
                <div className={styles.nonPaperMaterials}>
                    <header>
                        <p>电子材料</p>
                    </header>
                    <Row>
                        <Col span={24}>
                            <ul className={styles.materialList}>
                                {electronMaterials.map(item => {
                                    const { materialName, materialCode, materialValue } = item || {};
                                    return (
                                        <li key={materialCode}>
                                            <span>{materialName}：</span>
                                            <span>{materialValue || '--'}</span>
                                        </li>
                                    );
                                })}
                            </ul>
                        </Col>
                    </Row>
                </div>
                <div className={styles.paperMaterials}>
                    <header>
                        <p>实体材料</p>
                    </header>
                    <Row>
                        <Col span={24}>
                            <p>请收集以下实体材料的原件及扫描件：</p>
                            <Table
                                className={styles.paperMaterialsTable}
                                columns={columns}
                                rowKey="materialCode"
                                bordered
                                dataSource={entityMaterials}
                                pagination={false}
                            />
                        </Col>
                    </Row>
                </div>
            </Card>
            <Card
                headBorder
                bordered={false}
                extra={
                    canAction && (
                        <BottomAction>
                            <span className={styles.autoNotice}>自行通知行政负责人</span>
                            <Button onClick={handleCancel}>取消</Button>
                            <Button loading={loading} type="primary" onClick={handleSaveLaborContract}>
                                确定
                            </Button>
                        </BottomAction>
                    )
                }
                title={
                    <div className={styles.signPanelTitle}>
                        <span>签署劳动合同</span>
                        {laborContract.url && (
                            <div className={styles.diplomaDownload}>
                                <Tooltip {...contractProviewProps}>
                                    <Button
                                        type="link"
                                        className={styles.iconButton}
                                        onClick={() =>
                                            handlePreview({
                                                keyName: laborContract.keyName,
                                                url: laborContract.url,
                                                originName: laborContract.originName
                                            })
                                        }
                                    >
                                        预览
                                    </Button>
                                </Tooltip>
                                <span className={styles.splitLine} />
                                <Button
                                    type="link"
                                    className={styles.iconButton}
                                    onClick={() => {
                                        saveFile(laborContract.url, laborContract.originName);
                                    }}
                                >
                                    下载
                                </Button>
                            </div>
                        )}
                    </div>
                }
            >
                <Form {...formItemLayout} scrollToFirstError>
                    <Form.Item label="劳动合同">
                        {getFieldDecorator('isSignedContract', {
                            initialValue: !!isSigned,
                            rules: [
                                {
                                    required: true,
                                    validator: (rule, value, callback) => {
                                        if (value) {
                                            callback();
                                        } else {
                                            callback('劳动合同必选，请确认合同已签署');
                                        }
                                    }
                                }
                            ]
                        })(
                            <Checkbox checked={isSignedContractState} onChange={handleSignedChange}>
                                已与员工签订劳动合同
                            </Checkbox>
                        )}
                    </Form.Item>
                    <Form.Item label="上传其他附件">
                        {getFieldDecorator('otherContract', {
                            initialValue: otherFileList
                        })(
                            <UploadOss
                                uploadUrl="/api/resource/public/oss/producePutPreSignUrls"
                                dragAble={false}
                                fileList={otherFileList}
                                checkFileSize={10}
                                checkFileSizeMsg="文件大小不可超过10M，请重新选择"
                                sysCode="OA"
                                setFileList={showFileList => {
                                    setOtherFileList(showFileList);
                                }}
                                businessCode="SysAvatar"
                                categoryCode={otherMaterialsConfig?.categoryCode}
                                disabled={!canAction || fileUploading}
                                checkFileType={otherMaterialsConfig?.uploadFormatLimit}
                                checkFileTypeMsg={otherMaterialsConfig?.uploadFormatTip}
                                showPreviewFile
                                onUploaded={async (file = []) => {
                                    try {
                                        await UploadMaterialsFile({
                                            businessCode: 'EntryMaterials',
                                            entityId: entryPersonnelCode,
                                            list: [
                                                {
                                                    categoryCode: otherMaterialsConfig?.categoryCode,
                                                    keyNameAndOpt: [`ADD:${file[0]?.keyName}`]
                                                }
                                            ],
                                            sysCode: 'OA'
                                        });
                                    } catch (error) {
                                        message.error(error.message);
                                    }
                                }}
                                onRemove={(file = {}) => {
                                    handleDeleteFile({
                                        businessCode: 'EntryMaterials',
                                        categoryCode: otherMaterialsConfig?.categoryCode,
                                        ids: [entryPersonnelCode],
                                        keyName: file.keyName,
                                        sysCode: 'OA'
                                    });
                                }}
                            >
                                <Button
                                    type="default"
                                    ghost
                                    className={styles.uploadContractButton}
                                    disabled={!canAction || fileUploading}
                                >
                                    <IconFont icon="iconoa_form_bnt_upload" />
                                    上传文件
                                </Button>
                            </UploadOss>
                        )}
                    </Form.Item>
                </Form>
            </Card>
            <PreviewModal title ref={previewRef} height="650px" />
        </div>
    );
};

export default withRouter(Form.create()(HRLink));
